package com.wangjw.concurrency.example.syncContainer;

import com.wangjw.concurrency.annotations.NotThreadSafe;

import java.util.Iterator;
import java.util.Vector;

/**
 * Created by wangjw on 18/5/2.
 */
@NotThreadSafe
public class VectorExample3 {

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);

        test1(vector);
    }

    private static void test1(Vector<Integer> vector) { // foreach  -->  java.util.ConcurrentModificationException
        for (Integer i : vector) {
            if (i.equals(3)) {
                vector.remove(i);
            }
        }
    }

    private static void test2(Vector<Integer> vector) { // iterator  -->  java.util.ConcurrentModificationException
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            Integer i = iterator.next();
            if (i.equals(3)) {
                vector.remove(i);
            }
        }
    }

    // success
    private static void test3(Vector<Integer> vector) { // for
        for (int i = 0; i < vector.size(); i++) {
            if (vector.get(i).equals(3)) {
                vector.remove(i);
            }
        }
    }
}
